package com.other;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author wujunlin
 * @time 2024/7/8 22:03
 */
public class DesUtil {

    private static final String DES_ALGORITHM = "DES";
    public static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";

    /**
     * 加密
     *
     * @param data         需要加密的内容
     * @param secretKeyStr 密钥
     * @return 加密后的数据
     */
    public static String encrypt(String data, String secretKeyStr) {
        try {
            DESKeySpec desKeySpec = new DESKeySpec(secretKeyStr.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM);
            SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
        } catch (Exception e) {
            System.out.println(e.toString());
        }
       return "加密错误------";
    }

    /**
     * 解密
     *
     * @param data         需要解密的内容
     * @param secretKeyStr 密钥
     * @return 解密后的数据
     */

    public static String decrypt(String data, String secretKeyStr) {

        try {
            DESKeySpec desKeySpec = new DESKeySpec(secretKeyStr.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM);
            SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(cipher.doFinal(Base64.getDecoder().decode(data)), StandardCharsets.UTF_8);

        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("04444444444");
        }
        return "解密错误------";
    }


    public static void main(String[] args) throws Exception {
        String secretKey = "Ths@Hexin@10jqka";
        System.out.println(decrypt("OhSCc1Xt8l0=", secretKey));

        System.out.println(encrypt("270633", secretKey));
 
    }
}